(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.popup.documentListController', controller);
	controller.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig',
			'authService', '$filter', 'commonService', 'documentService' ];
	function controller($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService, $filter, commonService, documentService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("documentListPopup"), params;
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		params = ctrl.dialogsModule.params;
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		ctrl.init = function() {
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, rowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.searchCriteria.list';
			if(params.isViewPage) {
				ctrl.gridOptions.enableOperation = true;
				ctrl.gridOptions.addRow = null;
				ctrl.gridOptions.enableOperationRemoveSelected = false;
				ctrl.gridOptions.enableRowHeaderSelection = false;
			} else {
				ctrl.gridOptions.enableOperation = true;
				ctrl.gridOptions.enableOperationRemoveSelected = true;
			}
			ctrl.searchCriteria = ctrl.gridOptions.defaultSearchCriteria;
			ctrl.searchCriteria.storageSearchCriteria = false;
			documentService.initDocMimeTypeOptions(ctrl).then(function() {
				ctrl.search();
			});
		};
		
		ctrl.addAttachment = function(row) {
			//add attachement to document temp table.
			var defer = $q.defer();
			modalService.openCustomDialogs({
				'title' : 'title.dialogs.attachmentcreatepopup',
				'dialogsModule' : 'cda.popup.documentCreateController',
				'params' : params,
				'btnCallback' : {
					'ok' : function(obj) {
						//angular.merge(row, obj);
						//set tempDocIds
						params.tempDocIds = [];
						angular.forEach(ctrl.searchCriteria.list, function(object) {
							params.tempDocIds.push($filter('encode')(object.docId));
						});
						params.tempDocIds.push($filter('encode')(obj.docId));
						var relatedDocIdsProp = params.relatedDocIdsProp || "tempDocIds";
						if (params.entity) params.entity[relatedDocIdsProp] = params.tempDocIds;
						if(params.storeTempTableFlag) {
							params.isTemporary = 'Y';
						} else {
							params.isTemporary = 'N';
						}
						var resultParams = angular.merge(obj, params);
						authService.createSubmitAttachment(resultParams).then(function(){
							ctrl.search().then(function(){
								defer.reject();
							});
						}, failedFun);
					}
				}
			});
			return defer.promise;
		};

		function failedFun(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		ctrl.viewAttachment = function(resultObj) {
			modalService.openCustomDialogs({
				'title' : 'title.dialogs.attachmentviewpopup',
				'dialogsModule' : 'cda.popup.documentViewController',
				'params' : resultObj.entity,
				'btnCallback' : {
					'ok' : function(obj) {
					}
				}
			});
		};
		ctrl.removeAttachment = function() {
			var defer = $q.defer();
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.delete', args : [ctrl.selectedRows[0].docTitle]} ],
				'btnCallback' : {
					'ok' : function(response) {
						authService.deleteAttachment(ctrl.selectedRows[0]).then(function(){
							ctrl.search().then(function(){
								defer.reject();
							});
						}, failedFun);
					}
				}
			});
			return defer.promise;
		};
		ctrl.download = function(rowObj) {
			var param  = angular.copy(rowObj);
			commonService.download(param);
		};
		ctrl.openDocument = function(rowObj) {
			var param  = angular.copy(rowObj);
			commonService.openDocument(param);
		};
		ctrl.search = function() {
			var defer = $q.defer(); 
			ctrl.searchCriteria.list = [];
			if(params.entity) {
				var relatedDocIdsProp = params.relatedDocIdsProp || "tempDocIds";
				params.tempDocIds = params.entity[relatedDocIdsProp];
			}
			angular.forEach(params, function(value, key) {
				ctrl.searchCriteria[key] = value;
			});
			authService.getAttachmentList(ctrl.searchCriteria).then(function(response) {
				angular.merge(ctrl.searchCriteria, response.data);
				gridService.updateGridOptions(ctrl.searchCriteria, ctrl.gridOptions);
				defer.resolve();
			}, angular.noop);
			return defer.promise;
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.searchCriteria.pageNum = pageNum;
			ctrl.searchCriteria.pageSize = pageSize;
			ctrl.searchCriteria.list = [];
			ctrl.search();
		}

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}

		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.searchCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.searchCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
	}
})(angular);